package cn.ai.boot.config.PCF;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.*;

public class PCFParser {
    private List<String> lines;
    
    public PCFParser(String filePath) throws IOException {
        this.lines = Files.readAllLines(Paths.get(filePath));
    }

    // 获取键值(去除空格)
    public String getValue(String key) {
        Pattern pattern = Pattern.compile("^" + key + "\\s+(\\S+)");
        for (String line : lines) {
            Matcher matcher = pattern.matcher(line);
            if (matcher.find()) {
                return matcher.group(1).trim();
            }
        }
        return null;
    }

    // 替换所有匹配标识
    public void replaceAll(String oldStr, String newStr) {
        lines.replaceAll(line -> line.replaceAll(oldStr, newStr));
    }

    // 获取值匹配的行范围
    public List<int[]> getValueRanges(String value) {
        List<int[]> ranges = new ArrayList<>();
        Pattern valuePattern = Pattern.compile(".*" + value + ".*");
        
        for (int i = 0; i < lines.size(); i++) {
            if (valuePattern.matcher(lines.get(i)).matches()) {
                int start = findBlockStart(i);
                int end = findBlockEnd(i);
                ranges.add(new int[]{start, end});
            }
        }
        return ranges;
    }

    private int findBlockStart(int currentLine) {
        for (int i = currentLine; i >= 0; i--) {
            if (lines.get(i).trim().isEmpty() || 
                !lines.get(i).startsWith(" ")) {
                return i;
            }
        }
        return 0;
    }

    private int findBlockEnd(int currentLine) {
        for (int i = currentLine; i < lines.size(); i++) {
            if (lines.get(i).trim().isEmpty() || 
                !lines.get(i).startsWith(" ")) {
                return i - 1;
            }
        }
        return lines.size() - 1;
    }

    public void saveToFile(String path) throws IOException {
        Files.write(Paths.get(path), lines);
    }
}
